package com.zkjd.lingdong.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import com.zkjd.lingdong.data.FunctionsConfig
import com.zkjd.lingdong.repository.DeviceRepository
import com.zkjd.lingdong.service.BleService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

/**
 * 开机启动接收器，用于开机时自动启动后台服务
 */
@AndroidEntryPoint
class BootCompletedReceiver : BroadcastReceiver() {
    
    @Inject
    lateinit var deviceRepository: DeviceRepository
    
    private val receiverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
            Timber.tag("BootCompletedReceiver").d("收到开机广播")

            receiverScope.launch {
                // 启动服务
                Timber.tag("BootCompletedReceiver").d("启动后台服务")
                startBleService(context)
            }
        }
        else{

            if (FunctionsConfig.getInstance(context).getIs8295()) {
                val action = intent.action
                if (action == "mega.intent.action.VEHICLE_IGNITION_ON") {
                    Timber.tag("BootCompletedReceiver").d("收到开机广播2222")
                    startBleService(context)
                }
            }

        }
    }
    

    /**
     * 启动蓝牙服务
     */
    private fun startBleService(context: Context) {
        val serviceIntent = Intent(context, BleService::class.java)
        
        // 根据Android版本选择合适的启动方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent)
        } else {
            context.startService(serviceIntent)
        }
    }
} 